package com.codeant.bikeindicatorapplication.tools;

import android.content.Context;
import android.hardware.camera2.CameraManager;
import android.os.Build;

public class FlashLightHelper {

    private Boolean isFick = false;

    private CameraManager cm;

    public void init(Context context){
        cm = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    //开启闪烁
    public void fickOn(){
        isFick = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isFick) {
                    open();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    close();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    //关闭闪烁
    public void fickOff(){
        isFick = false;
    }

    //打开闪光灯
    public void open() {
        try {
            if (cm != null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//Android 6 以上
                    cm.setTorchMode("0",true);//0,指cameraId,通常0代表后置，1代表前置
                }else {

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭闪光灯
    public void close() {
        try {
            if (cm != null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    cm.setTorchMode("0",false);//0,指cameraId,通常0代表后置，1代表前置
                }else {

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
